<template>
  <div class="full-width-layout">
    <header class="header">
      <div class="header-container">
        <div class="logo">
          <router-link to="/">我的博客</router-link>
        </div>
        <nav class="nav">
          <router-link to="/" class="nav-item" exact-active-class="router-link-exact-active">首页</router-link>
          <template v-for="category in categoryStore.categories" :key="category.id">
            <router-link :to="`/category/${category.id}`" class="nav-item">{{ category.name }}</router-link>
          </template>
          <router-link to="/timeline" class="nav-item">时间轴</router-link>
        </nav>
        <div class="user-section">
          <!-- 未登录状态显示登录按钮 -->
          <a-button v-if="!userStore.isLoggedIn" type="primary" @click="showLoginModal" class="login-btn">
            <i class="icon-user"></i> 登录
          </a-button>
          
          <!-- 已登录状态显示用户头像和下拉菜单 -->
          <a-dropdown v-else :trigger="['hover']">
            <div class="user-avatar">
              <img :src="getStaticUrl(userStore.userInfo.avatar)" alt="用户头像">
              <span class="user-name">{{ userStore.userInfo?.username || '用户' }}</span>
              <i class="icon-dropdown"></i>
            </div>
            <template #overlay>
              <a-menu>
                <a-menu-item key="backend">
                  <router-link to="/backend">
                    <i class="icon-backend"></i> 后台管理
                  </router-link>
                </a-menu-item>
                <a-menu-item key="profile">
                  <router-link to="/user/profile">
                    <i class="icon-profile"></i> 个人资料
                  </router-link>
                </a-menu-item>
                <a-menu-item key="articles">
                  <router-link to="/user/articles">
                    <i class="icon-articles"></i> 我的文章
                  </router-link>
                </a-menu-item>
                <a-menu-item key="settings">
                  <router-link to="/user/settings">
                    <i class="icon-settings"></i> 账号设置
                  </router-link>
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="logout" @click="handleLogout">
                  <i class="icon-logout"></i> 退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </header>
    
    <div class="main-container">
      <main class="main-content">
        <router-view></router-view>
      </main>
    </div>
    
    <footer class="footer">
      <!-- 保持与MainLayout相同的页脚 -->
      <div class="footer-wave">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
          <path fill="#ffffff" fill-opacity="1" d="M0,192L48,176C96,160,192,128,288,122.7C384,117,480,139,576,149.3C672,160,768,160,864,138.7C960,117,1056,75,1152,69.3C1248,64,1344,96,1392,112L1440,128L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path>
        </svg>
      </div>
      
      <!-- 这里放页脚内容，与主布局相同 -->
    </footer>
    
    <!-- 添加登录模态框 -->
    <a-modal v-model:visible="loginModalVisible" title="登录" @cancel="closeLoginModal" :footer="null" width="400px">
      <a-form :model="loginForm" @finish="handleLogin">
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="loginForm.username" placeholder="用户名">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="loginForm.password" placeholder="密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item name="remember">
          <a-checkbox v-model:checked="loginForm.remember">记住我</a-checkbox>
          <a style="float: right;">忘记密码?</a>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" class="login-button" :loading="loginLoading">登录</a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-form-footer">
        <span>还没有账号? <a @click="showRegisterModal">立即注册</a></span>
      </div>
    </a-modal>
    
    <!-- 注册模态框 -->
    <a-modal v-model:visible="registerModalVisible" title="注册" @cancel="closeRegisterModal" :footer="null" width="400px">
      <a-form :model="registerForm" @finish="handleRegister">
        <a-form-item
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="registerForm.username" placeholder="用户名">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input v-model:value="registerForm.email" placeholder="邮箱">
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>
        
        <a-form-item
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]"
        >
          <a-input-password v-model:value="registerForm.password" placeholder="密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item
          name="confirmPassword"
          :rules="[
            { required: true, message: '请确认密码' },
            { validator: validateConfirmPassword }
          ]"
        >
          <a-input-password v-model:value="registerForm.confirmPassword" placeholder="确认密码">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" class="login-button" :loading="registerLoading">注册</a-button>
        </a-form-item>
      </a-form>
      
      <div class="login-form-footer">
        <span>已有账号? <a @click="showLoginModal">立即登录</a></span>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, provide, inject } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useCategoryStore } from '@/stores/category';
import { useUserStore } from '@/stores/user';
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons-vue';
import { getStaticUrl } from '@/utils/url';

const router = useRouter();
const categoryStore = useCategoryStore();
const userStore = useUserStore();

// 登录相关方法和状态
const loginModalVisible = ref(false);
const loginLoading = ref(false);
const registerModalVisible = ref(false);
const registerLoading = ref(false);

const loginForm = ref({
  username: '',
  password: '',
  remember: false
});

const registerForm = ref({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
});

// 提供显示登录模态框的方法
const showLoginModal = () => {
  registerModalVisible.value = false; // 确保注册模态框关闭
  loginModalVisible.value = true;
};

// 提供显示注册模态框的方法
const showRegisterModal = () => {
  loginModalVisible.value = false; // 确保登录模态框关闭
  registerModalVisible.value = true;
};

// 使用provide提供方法给后代组件
provide('showLoginModal', showLoginModal);
provide('showRegisterModal', showRegisterModal);

onMounted(async () => {
  await categoryStore.fetchCategories();
  if (localStorage.getItem('token')) {
    await userStore.getUserInfo();
  }
});

// 其他方法与MainLayout相同
const closeLoginModal = () => {
  loginModalVisible.value = false;
  loginForm.value = {
    username: '',
    password: '',
    remember: false
  };
};

const closeRegisterModal = () => {
  registerModalVisible.value = false;
  registerForm.value = {
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  };
};

const validateConfirmPassword = async (rule, value) => {
  if (value !== registerForm.value.password) {
    throw new Error('两次输入的密码不一致');
  }
};

const handleLogin = async (values) => {
  try {
    loginLoading.value = true;
    await userStore.login(values);
    message.success('登录成功');
    closeLoginModal();
  } catch (error) {
    message.error('登录失败，请检查用户名和密码');
    console.error('登录失败:', error);
  } finally {
    loginLoading.value = false;
  }
};

const handleRegister = async () => {
  try {
    registerLoading.value = true;
    // 调用注册API
    message.success('注册成功，请登录');
    closeRegisterModal();
    showLoginModal();
  } catch (error) {
    console.error('注册失败:', error);
    message.error('注册失败');
  } finally {
    registerLoading.value = false;
  }
};

const handleLogout = async () => {
  try {
    await userStore.logout();
    message.success('已成功退出登录');
    router.push('/');
  } catch (error) {
    message.error('退出登录失败');
    console.error('退出登录失败:', error);
  }
};
</script>

<style scoped>
/* 复用MainLayout的样式，除了需要调整的内容区域 */
.full-width-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.header {
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo a {
  font-size: 1.5rem;
  font-weight: bold;
  color: #42b983;
  text-decoration: none;
}

.nav {
  display: flex;
  margin-left: 40px;
  gap: 20px;
}

.nav-item {
  color: #333;
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  position: relative;
  padding: 0 4px;
  transition: all 0.3s;
}

/* 只有精确匹配和悬停时才应用激活样式 */
.nav-item:hover, .nav-item.router-link-exact-active {
  color: #42b983;
}

.nav-item:hover::after, .nav-item.router-link-exact-active::after {
  width: 100%;
}

/* 移除非精确匹配的激活样式 */
.nav-item.router-link-active:not(.router-link-exact-active) {
  color: #333;
}

.nav-item.router-link-active:not(.router-link-exact-active)::after {
  width: 0;
}

.nav-item::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #42b983;
  transition: width 0.3s;
}

.main-container {
  flex: 1;
  background-color: #f8f9fa;
  padding: 20px;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 添加用户头像样式 */
.user-section {
  display: flex;
  align-items: center;
}

.login-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  background-color: #42b983;
  border-color: #42b983;
}

.login-btn:hover {
  background-color: #3da776;
  border-color: #3da776;
}

.icon-user::before {
  content: '👤';
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 20px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-name {
  margin-left: 8px;
  font-weight: 500;
  color: #333;
}

.icon-dropdown {
  margin-left: 4px;
  font-size: 12px;
  color: #999;
}

.icon-dropdown::after {
  content: '▼';
  font-size: 8px;
}

/* 下拉菜单图标 */
.icon-profile::before { content: '👤'; margin-right: 8px; }
.icon-articles::before { content: '📝'; margin-right: 8px; }
.icon-settings::before { content: '⚙️'; margin-right: 8px; }
.icon-logout::before { content: '🚪'; margin-right: 8px; }
.icon-backend::before { content: '🏠'; margin-right: 8px; }
/* 登录/注册模态框相关样式 */
.login-button {
  width: 100%;
}

.login-form-footer {
  text-align: center;
  margin-top: 16px;
}

.login-form-footer a {
  color: #1890ff;
  cursor: pointer;
}

.login-form-footer a:hover {
  color: #40a9ff;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .user-name {
    display: none;
  }
}
</style> 